Method Overriding And Constructor Overriding In Javascript

Posted on August 23, 2025 by Vishesh Namdev
Python C C++ Javascript Java
Inheritance in JS

Method Overriding

Method overriding happens when a child class defines a method with the same name as a parent class method. When we call that method on the child object, the childโ€™s version gets executed, not the parentโ€™s.

Example of Inheritance

class RailwayForm {
    submit() {
        console.log("Form submitted at the station counter.");
    }
}

class OnlineRailwayForm extends RailwayForm {
    // Method Overriding
    submit() {
        console.log("Form submitted online with digital signature.");
    }
}

let offline = new RailwayForm();
offline.submit(); // Output: Form submitted at the station counter.

let online = new OnlineRailwayForm();
online.submit();  // Output: Form submitted online with digital signature.
Explanation:-
  • Both classes have a submit() method.
  • But when we call submit() on OnlineRailwayForm, the childโ€™s version overrides the parentโ€™s.
  • This is Method Overriding.
  • We use this when we want the child class to customize or change the behavior of an inherited method.

    Method Overriding

  • In JavaScript, constructors are special methods used for initializing objects.
  • When a child class defines its own constructor, it overrides the parentโ€™s constructor.
  • But hereโ€™s the catch: The child constructor must call super() first before using this.
  • Example:-

    class RailwayForm {
        constructor(name, trainNo) {
            this.name = name;
            this.trainNo = trainNo;
        }
        submit() {
            console.log(`${this.name}'s form submitted for train ${this.trainNo}.`);
        }
    }
    class OnlineRailwayForm extends RailwayForm {
        constructor(name, trainNo, email) {
            // Call parent constructor first
            super(name, trainNo);
            this.email = email;
        }
        submit() {
            // Call parent method
            super.submit();
            // Add extra steps
            console.log(`Confirmation email sent to ${this.email}.`);
        }
    }
    let onlineForm = new OnlineRailwayForm("Rohan", 12210, "rohan@example.com");
    onlineForm.submit();
    Explanation:-
  • RailwayForm has a constructor that sets name and train number.
  • OnlineRailwayForm overrides the constructor to add email.
  • It calls super() to reuse parent initialization and then extends it.
  • This is Constructor Overriding โ€” customizing the way objects are created.

    Difference Between Method and Constructor Overriding

    Difference between method Overriding and Constructor Overriding in JS
    ๐Ÿ“ขImportant Note๐Ÿ“ข

    How did you feel about this post?

    ๐Ÿ˜ ๐Ÿ™‚ ๐Ÿ˜ ๐Ÿ˜• ๐Ÿ˜ก

    Was this helpful?

    ๐Ÿ‘ ๐Ÿ‘Ž